<?php

require_once('includes/config.php');
require_once('libraries/database/impl/MySQLAdapter.php');

require_once('PHPUnit/Framework/TestCase.php');

/**
 * MySQLAdater test case.
 */
class MySQLAdaterTest extends PHPUnit_Framework_TestCase {
	
	/**
	 * @var MySQLAdater
	 */
	private $dbManager;
	
	/**
	 * Prepares the environment before running a test.
	 */
	protected function setUp() {
		parent::setUp ();
		$this->dbManager = new MySQLAdater(TEST_DB_USER, TEST_DB_PASS, TEST_DB_HOST, TEST_DB_DATABASE);
		$query = "CREATE TABLE IF NOT EXISTS userLevels (id int(11) NOT NULL, level varchar(255) NOT NULL, PRIMARY KEY (id), UNIQUE KEY level (level)) ENGINE=InnoDB";
		$this->dbManager->query($query);
	}
	
	/**
	 * Cleans up the environment after running a test.
	 */
	protected function tearDown() {
		$this->dbManager->Query("DROP TABLE userLevels");
		$this->dbManager = null;
		parent::tearDown ();
	}
	
	/**
	 * Tests MySQLAdater->Optimize()
	 */
	public function testOptimize() {
		$this->dbManager->Optimize("userLevels");
		$this->assertGreaterThan(0, $this->dbManager->getAffectedRows(), "Didn't do anything.");
	}
	
	/**
	 * Tests MySQLAdater->Insert()
	 */
	public function testInsert() {
		$this->dbManager->insert("userLevels", array("id" => 1, "level" => "Basic"));
		$this->assertGreaterThan(0, $this->dbManager->getAffectedRows(), "Didn't do anything.");
	}
	
	/**
	 * Tests MySQLAdater->Update()
	 */
	public function testUpdate() {
		$this->dbManager->insert("userLevels", array("id" => 1, "level" => "Basic"));
		$this->assertGreaterThan(0, $this->dbManager->getAffectedRows(), "Didn't do anything.");
		$this->dbManager->update("userLevels", array("level" => "Advanced"), array("id" => 1));
		$this->assertGreaterThan(0, $this->dbManager->getAffectedRows(), "Didn't do anything.");
	}
	
	/**
	 * Tests MySQLAdater->Delete()
	 */
	public function testDelete() {
		$this->dbManager->insert("userLevels", array("id" => 1, "level" => "Basic"));
		$this->assertGreaterThan(0, $this->dbManager->getAffectedRows(), "Didn't do anything.");
		$this->dbManager->delete("userLevels", array("id" => 1));
		$this->assertGreaterThan(0, $this->dbManager->getAffectedRows(), "Didn't do anything.");
	}
	
	/**
	 * Tests MySQLAdater->CheckExists()
	 */
	public function testCheckExists() {
		$this->dbManager->insert("userLevels", array("id" => 1, "level" => "Basic"));
		$this->assertGreaterThan(0, $this->dbManager->getAffectedRows(), "Didn't do anything.");
		$this->assertTrue($this->dbManager->checkExists(array("userLevels"), array("id" => 1)), "It's not there.");
	}
	
	/**
	 * Tests MySQLAdater->Sterilize()
	 */
	public function testSterilize() {
		$badString = "This is a 'String' to sterilIze.";
		$result = "This is a \\'String\\' to sterilIze.";
		$goodString = $this->dbManager->sterilize($badString);
		$this->assertEquals($result, $goodString);
	}

}

